﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkAssetManager.Entity;
using System.Management;
using log4net; 
namespace NetworkAssetManager.WMI
{
    class StartUp
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(StartUp));

        private static EntStartUp FillDetails(ManagementBaseObject obj)
        {
            EntStartUp objEntStartUp = new EntStartUp();
            try
            {
                objEntStartUp.Command = WMIUtil.ToString(obj["Command"]); 
            }
            catch (Exception)
            {
                objEntStartUp.Command = ""; 
            }

            try
            {
                objEntStartUp.Location = WMIUtil.ToString(obj["Location"]);
            }
            catch (Exception)
            {
                objEntStartUp.Location = "";
            }

            try
            {
                objEntStartUp.Name = WMIUtil.ToString(obj["Name"]);
            }
            catch (Exception)
            {
                objEntStartUp.Name = "";
            }

            try
            {
                objEntStartUp.StartUpUser = WMIUtil.ToString(obj["User"]);
            }
            catch (Exception)
            {
                objEntStartUp.StartUpUser = "";
            }

            return objEntStartUp;
        }
        
        public static List<EntStartUp>GetStartUpDetails(ManagementScope scope)
        {
            _logger.Info("Collecting startup details for machine " + scope.Path.Server);

            ObjectQuery query = null;
            ManagementObjectSearcher searcher = null;
            ManagementObjectCollection objects = null;
            List<EntStartUp> lstStartUp = new List<EntStartUp>();

            try
            {
                query = new ObjectQuery("select * from Win32_StartupCommand where User != '.DEFAULT' and User != 'NT AUTHORITY\\\\SYSTEM'");
                searcher = new ManagementObjectSearcher(scope, query);
                objects = searcher.Get();
                lstStartUp.Capacity = objects.Count;
                foreach (ManagementBaseObject obj in objects)
                {
                    lstStartUp.Add(FillDetails(obj));
                    obj.Dispose();
                }

            }
            catch (System.Exception e)
            {
                _logger.Error("Exception in startup collection " + e.Message);
            }
            finally
            {
                searcher.Dispose();
            }
            return lstStartUp;
        }    
    }
}
